package com.demo.juc.order;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: shubin_yao
 * @Date: 2022/04/30/18:22
 * @Description: 资源类
 *  实际际业务场景 ：下订单--> 减库存 --》调支付
 * <p>
 * 顺序执行方案：
 *
 * (1) 非阻塞模型
 * 采用新版Lock-condition 设置标志位，精准唤醒
 *
 *
 */
public class ShareResource {

    private String flg = "A";

    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void print5() throws InterruptedException {
        lock.lock();
        try {
            if (!flg.equals("A")) {
                condition1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() +"\t"+ i);
            }
            flg = "B";
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print10() throws InterruptedException {
        lock.lock();
        try {
            if (!flg.equals("B")) {
                condition2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() +"\t"+ i);
            }
            flg = "C";
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print15() throws InterruptedException {
        lock.lock();
        try {
            if (!flg.equals("C")) {
                condition3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() +"\t"+ i);
            }
            flg = "A";
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }
}
